//
//  YWEwinManager.m
//  maintain
//
//  Created by Kyo on 16/7/1.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWEwinManager.h"
#import "YWLoginUser.h"
#import "YWLoginTool.h"
#import "YWCommonTool.h"
#import "WMHttpTool.h"
#import "MJExtension.h"
#import "YWConst.h"
#import "YWMacro.h"
#import "YWDeviceInfo.h"
#import "NSDate+Additions.h"
#import "YWEwinDBManager.h"

#import "YWNoticeManager.h"
#import "YWTempMissionManager.h"
#import "YWMissionManager.h"
#import "YWKeepWatchMissionManager.h"
#import "YWInspectionMissionManager.h"
#import "YWDetectAndUpkeepManager.h"
#import "YWMeterReadingManager.h"
#import "YWAttendanceManager.h"
#import "YWMissionManager.h"
#import "YWMaterialManager.h"
#import "YWUnReadCount.h"
#import "YWLastReadTime.h"
#import "YWNotifyManager.h"
#import "YWNoQrcodeRights.h"
#import "YWReportTroubleManager.h"
#import "YWTroubleMissionManager.h"

@interface YWEwinManager ()
//@property (nonatomic, strong) dispatch_queue_t serialQueue;
@end

@implementation YWEwinManager
YWSingletonM(Manager)

//- (dispatch_queue_t)serialQueue
//{
//    if (!_serialQueue) {
//        _serialQueue = dispatch_queue_create("requestNewMissionNoReadCount", DISPATCH_QUEUE_SERIAL); //创建上传串行队列
//    }
//    return _serialQueue;
//}

// 获取设备信息
- (YWDeviceInfo*)deviceInfo{
    UIDevice* device = [UIDevice currentDevice];
    YWDeviceInfo* info = [[YWDeviceInfo alloc] init];
    info.apiVersion = [NSString stringWithFormat:@"IOS %@", device.systemVersion];
    info.model = [YWCommonTool platformStringOfDevice];
    info.resolution = NSStringFromCGSize([UIScreen mainScreen].currentMode.size);
    info.screen = [YWCommonTool inchOfDevice];
    info.network = [YWCommonTool netType];
    info.appVersion = [NSString stringWithFormat:@"v%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString*)kCFBundleVersionKey]];
    info.deviceType = @"ios";
    return info;
}

- (void)requestLoginUserInfoWithComplete:(void (^)(NSInteger))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(0);}return;}
    
    [[WMHttpTool shareHttpTool] getWithUrl:[YWCommonTool loginUserInfoUrl] params:nil success:^(NSHTTPURLResponse* response, id json) {
        NSDictionary* userJson = [[NSDictionary alloc] initWithDictionary:json];
        YWLoginUser* user = [YWLoginUser mj_objectWithKeyValues:userJson];
        if (user && user.uniqueId > 0) {
            YWLoginUser *currentUser = [YWLoginTool loginUser];
            currentUser.userName = user.userName;
            currentUser.headIcon = user.headIcon;
            currentUser.mobile = user.mobile;
            currentUser.isTroubleServer = user.isTroubleServer;
            [YWLoginTool saveLoginOfUser:currentUser];
        }
        if (complete) {
            complete(response.statusCode);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        YWLog(@"%s,error:%@", __func__, error.userInfo);
        if (complete) {
            complete(response.statusCode);
        }
    }];
}

- (void)uploadDeviceInfoWithDeviceToken:(NSString *)deviceToken IsLogin:(NSInteger)isLogin WithComplete:(void (^)(NSInteger statusCode))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(0);}return;}
    
    YWDeviceInfo* deviceInfo = [[YWEwinManager shareManager] deviceInfo];
    NSString *localVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString* newlocalVersion = [localVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
    NSDictionary* params = @{ @"model" : deviceInfo.model,
                              @"apiVersion" : deviceInfo.apiVersion,
                              @"screen" : deviceInfo.screen,
                              @"resolution" : deviceInfo.resolution,
                              @"network" : deviceInfo.network,
                              @"appVersion" : newlocalVersion?:@"397",
                              @"deviceToken" : deviceToken.length == 0 ? @"" : deviceToken,
                              @"deviceType" : deviceInfo.deviceType,
                              @"isLogin" : @(isLogin)
                              };
    NSString *url = [YWCommonTool getUploadDeviceInfoUrl];
    YWLog(@"url:%@,params:%@",url,params);
    [[WMHttpTool shareHttpTool] postWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        if (complete) {
            complete(response.statusCode);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        YWLog(@"%s,error:%@", __func__, error.userInfo);
        if (complete) {
            complete(response.statusCode);
        }
    }];
}

- (void)requestLogoutWithDeviceToken:(NSString *)deviceToken WithComplete:(void (^)(NSInteger))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(0);}return;}
    
    NSDictionary* params = @{@"deviceToken" : deviceToken.length == 0 ? @"" : deviceToken};
    YWLog(@"requestLogoutWithDeviceToken : %@",deviceToken);
    [[WMHttpTool shareHttpTool] postWithUrl:[YWCommonTool logoutUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
        if (complete) {
            complete(response.statusCode);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        YWLog(@"%s,error:%@", __func__, error.userInfo);
        if (complete) {
            complete(response.statusCode);
        }
    }];
}

- (void)requestDatas{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *inspectionMissionIds = [[YWInspectionMissionManager shareManager] allInspectionMissionIds];
        if (inspectionMissionIds.length) {
            [[YWInspectionMissionManager shareManager] requestInspectionMissionStatusWithIds:inspectionMissionIds Complete:nil];
        }
        NSString *keepWatchMissionIds = [[YWKeepWatchMissionManager shareManager] allKeepWatchMissionIds];
        if (keepWatchMissionIds.length) {
            [[YWKeepWatchMissionManager shareManager] requestKeepWatchMissionStatusWithIds:keepWatchMissionIds Complete:nil];
        }
        //获取用户身份信息
        [[YWEwinManager shareManager] requestLoginUserInfoWithComplete:nil];
        [YWDetectAndUpkeepManager updateDetectAndUpkeepMissionStatus];
        [[YWTroubleMissionManager shareManager] updateTroubleMissionModelStatus];
    });
}

- (void)requesNoQrcodeRightsWithBlock:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    [[WMHttpTool shareHttpTool] getWithUrl:[YWCommonTool noQrcodeRightsUrl] params:nil success:^(NSHTTPURLResponse* response, id json) {
        NSArray *noQrCodeRightsArray = [YWNoQrcodeRights mj_objectArrayWithKeyValuesArray:json];
        [noQrCodeRightsArray enumerateObjectsUsingBlock:^(YWNoQrcodeRights*  _Nonnull noQrcodeRight, NSUInteger idx, BOOL * _Nonnull stop) {
            //保存无二维码权限
            id object = @(noQrcodeRight.value);
            NSString *key = nil;
            if (noQrcodeRight.moduleId == YWNoQrcodeTypeKeepWatch) {
                //巡更
                key = KYWNoQrcodeTypeKeepWatchKey;
            }else if (noQrcodeRight.moduleId == YWNoQrcodeTypeInspection){
                //巡查
                key = KYWNoQrcodeTypeInspectionKey;
            }else if (noQrcodeRight.moduleId == YWNoQrcodeTypeDetection){
                //检测
                key = KYWNoQrcodeTypeDetectionKey;
            }else if (noQrcodeRight.moduleId == YWNoQrcodeTypeUpkeep){
                //保养
                key = KYWNoQrcodeTypeUpkeepKey;
            }else if (noQrcodeRight.moduleId == YWNoQrcodeTypeFixTrouble){
                //维修
                key = KYWNoQrcodeTypeFixTroubleKey;
            }else if (noQrcodeRight.moduleId == YWNoQrcodeTypeCheckRecord){
                //清点
                key = KYWNoQrcodeTypeCheckRecordKey;
            }else if (noQrcodeRight.moduleId == YWNoQrcodeTypeMeterReading){
                //抄表
                key = KYWNoQrcodeTypeMeterReadingKey;
            }else if (noQrcodeRight.moduleId == YWNoQrcodeTypeAttendance){
                //签到
                key = KYWNoQrcodeTypeAttendanceKey;
            }
            if (object && key) {
                [[NSUserDefaults standardUserDefaults] setObject:object forKey:key];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
        }];
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        YWLog(@"%s,error:%@", __func__, error.userInfo);
        if (complete) {
            complete(NO);
        }
    }];
}

- (void)netWorkStatusChange:(BOOL)existNetwork
{
    if (existNetwork) {
        if ([YWLoginTool isLogin]) {
            BOOL kNetWorkType = [[[NSUserDefaults standardUserDefaults] objectForKey:KNetWorkType] boolValue];
            if ([[WMHttpTool shareHttpTool] networkType] != WMNetworkTypeWiFi && kNetWorkType == NO) {
                return;
            }
            //检测，保养
            [[YWDetectAndUpkeepManager alloc] uploadFailedDetectAndUpkeepRecords];
            //报障
            [[YWReportTroubleManager shareManager] startUnUploadReportTrouble];
            //维修
            [[YWTroubleMissionManager shareManager] startUnUploadTroubleMissionRecord];
            //巡更
            [[YWKeepWatchMissionManager shareManager] uploadFailPatrolPointRecords];
            //巡查
            [[YWInspectionMissionManager shareManager] uploadFailInspectionRecords];
            //抄表
            [[YWMeterReadingManager shareManager] uploadFailMeterReadingRecords];
            //签到（签到改成在线签到）
//            [[YWAttendanceManager shareManager] uploadFailAttendanceInfo];
//            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//            dispatch_group_t group = dispatch_group_create();
//            dispatch_group_async(group, queue, ^{
//                //检测，保养
//                [[YWDetectAndUpkeepManager alloc] uploadFailedDetectAndUpkeepRecords];
//            });
//            dispatch_group_async(group, queue, ^{
//                //报障
//                [[YWReportTroubleManager shareManager] startUnUploadReportTrouble];
//            });
//            dispatch_group_async(group, queue, ^{
//                //维修
//                [[YWTroubleMissionManager shareManager] startUnUploadTroubleMissionRecord];
//            });
//            dispatch_group_async(group, queue, ^{
//                //巡更
//                [[YWKeepWatchMissionManager shareManager] uploadFailPatrolPointRecords];
//            });
//            dispatch_group_async(group, queue, ^{
//                //巡查
//                [[YWInspectionMissionManager shareManager] uploadFailInspectionRecords];
//            });
//            dispatch_group_async(group, queue, ^{
//                //抄表
//                [[YWMeterReadingManager shareManager] uploadFailMeterReadingRecords];
//            });
//            dispatch_group_async(group, queue, ^{
//                //签到
//                [[YWAttendanceManager shareManager] uploadFailAttendanceInfo];
//            });
//            dispatch_group_notify(group, dispatch_get_main_queue(), ^{
//            当dispatch_group_async的block里面执行的是异步任务，如果还是使用上面的方法你会发现异步任务还没跑完就已经进入到了dispatch_group_notify方法里面了，这时用到dispatch_group_enter和dispatch_group_leave就可以解决这个问题
//                YWLog(@"所有离线任务上传完毕！");
//            });
        }
    }
}

- (BOOL)saveEwinMenuWithArray:(NSArray*)menuArray{
    return [[YWEwinDBManager shareManager] saveEwinMenuWithArray:menuArray];
}

- (NSArray*)ewinMenuWithMenuEnName:(NSString*)enName{
    return [[YWEwinDBManager shareManager] ewinMenuWithMenuEnName:enName];
}

- (NSString*)menuNameWithPersimissionMenuName:(NSString*)name{
    NSString *retureName = @"";
    if ([name isEqualToString:@"新建通知"]) {
        retureName = @"发送通知";
    }else if ([name isEqualToString:@"create_work_task"]){
        retureName = @"发送临时任务";
    }
    else if ([name isEqualToString:@"新建巡查任务"]) {
        retureName = @"分配巡查任务";
    }
    else if ([name isEqualToString:@"check_inspection_record"]) {
        retureName = @"查看巡查记录";
    }
    else if ([name isEqualToString:@"巡查路线管理"]) {
        retureName = @"巡查路线管理";
    }
    else if ([name isEqualToString:@"新建巡更任务"]) {
        retureName = @"分配巡更任务";
    }
    else if ([name isEqualToString:@"check_keep_watch_record"]) {
        retureName = @"查看巡更记录";
    }
    else if ([name isEqualToString:@"巡更路线管理"]) {
        retureName = @"巡更路线管理";
    }
    else if ([name isEqualToString:@"新建保养任务"]) {
        retureName = @"分配保养任务";
    }
    else if ([name isEqualToString:@"新建检测任务"]) {
        retureName = @"分配检测任务";
    }
    return retureName;
}

//减少工作提醒对于推送的依赖，启动时查询新的任务
- (void)selectIsExistNewMissionsUnReadCount{
    NSDictionary *dic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = dic;
    if (dic == nil) {return;}
    
    YWLastReadTime *lastReadTime = [[YWEwinDBManager shareManager] lastReadTime];
    NSDictionary* params = lastReadTime ? @{
    @"noticeTime" : @(lastReadTime.noticeTime),@"taskTime" : @(lastReadTime.taskTime),
    @"troubleTime" : @(lastReadTime.troubleTime),
    @"fixTroubleTime" : @(lastReadTime.fixTroubleTime),
    @"inspectionTime" : @(lastReadTime.inspectionTime),
    @"keepWatchTime" : @(lastReadTime.keepWatchTime),
    @"upkeepTime" : @(lastReadTime.upkeepTime),
    @"detectionTime" : @(lastReadTime.detectionTime),
    @"materialTime" : @(lastReadTime.materialTime),
    @"remindTime" : @(lastReadTime.remindTime),
    @"warnTime" : @(lastReadTime.monitorAlarmTime)} : nil;
    NSString *url = [YWCommonTool unReadCountUrl];
    YWLog(@"所有模块未读数url:%@,params:%@",url,@"略");
    
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        YWUnReadCount* unReadCount = [YWUnReadCount mj_objectWithKeyValues:json];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //保存未读数
            [YWLoginTool saveNoticeWithNoRedCount:unReadCount.noticeCount];
            [YWLoginTool saveTempMissionWithNoRedCount:unReadCount.taskCount];
            [YWLoginTool saveReportTroubleWithNoReadCount:unReadCount.troubleCount];
            [YWLoginTool saveMissionNoRedCountWithMaintenanceType:YWMaintenanceTypeTrouble noReadCount:unReadCount.fixTroubleCount];
            [YWLoginTool saveMissionNoRedCountWithMaintenanceType:YWMaintenanceTypePatrol noReadCount:unReadCount.inspectionCount];
            [YWLoginTool saveMissionNoRedCountWithMaintenanceType:YWMaintenanceTypeKeepWatch noReadCount:unReadCount.keepWatchCount];
            [YWLoginTool saveMissionNoRedCountWithMaintenanceType:YWMaintenanceTypeUpkeep noReadCount:unReadCount.upkeepCount];
            [YWLoginTool saveMissionNoRedCountWithMaintenanceType:YWMaintenanceTypeDetection noReadCount:unReadCount.detectionCount];
            [YWLoginTool saveMaterialWithNoReadCount:unReadCount.materialCount];
            [YWLoginTool saveWorkReminderNoRedWithCount:unReadCount.remindCount];
            [YWLoginTool saveMonitorAlarmNoRedWithCount:unReadCount.warnCount];
            //保存总数
            [[YWEwinDBManager shareManager] updateTotalCount:unReadCount];
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:KPostGrabTroubleBillTotalCountNotification object:nil];
                [[YWNotifyManager shareManager] postPushNoticeNotify:nil];
                [[YWNotifyManager shareManager] postPushTempMissionNotify:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:KPostReportTroubleNoReadCountNotification object:nil];
                [[YWNotifyManager shareManager] postAssignKeepWatchMissionNotify];
                [[YWNotifyManager shareManager] postAssignInspectMissionNotify];
                [[YWNotifyManager shareManager] postAssignDetectMissionNotify];
                [[YWNotifyManager shareManager] postAssignUpKeepMissionNotify];
                [[YWNotifyManager shareManager] postRequestTroubleMissionNotify:0];
                [[NSNotificationCenter defaultCenter] postNotificationName:KPostMaterialNoReadCountNotification object:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:KPostWorkRmindUnReadCountNotification object:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:KPostMonitorAlarmUnReadCountNotification object:nil];
            });
        });
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        YWLog(@"%s,error:%@", __func__, error.userInfo);
    }];
}

- (BOOL)saveLastReadTime:(NSTimeInterval)lastReadTime type:(YWUnReadCountType)unReadType{
    return [[YWEwinDBManager shareManager] saveLastReadTime:lastReadTime type:unReadType];
}

- (BOOL)updateTotalCount:(YWUnReadCount*)unreadCount{
    return [[YWEwinDBManager shareManager] updateTotalCount:unreadCount];
}

- (YWUnReadCount*)totalCount{
    return [[YWEwinDBManager shareManager] totalCount];
}

- (void)addTotalCountWithType:(YWUnReadCountType)unReadType{
    return [[YWEwinDBManager shareManager] addTotalCountWithType:unReadType];
}

- (void)subtractTotalCountWithType:(YWUnReadCountType)unReadType{
    return [[YWEwinDBManager shareManager] subtractTotalCountWithType:unReadType];
}


- (void)addObserver:(YWHandler*)handler relationId:(NSString*)relationId type:(NSInteger)type complete:(void(^)(BOOL succeed))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    NSDictionary* params = @{@"relationId" : relationId,
                             @"uniqueId": @(handler.uniqueId),
                             @"type": @(type)};
    YWLog(@"%@",params);
    [[WMHttpTool shareHttpTool] postWithUrl:[YWCommonTool observerUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        YWLog(@"%s,error:%@", __func__, error.userInfo);
        if (complete) {
            complete(NO);
        }
    }];
}

- (void)deleteObserver:(YWHandler*)handler relationId:(NSString*)relationId type:(NSInteger)type complete:(void(^)(BOOL succeed))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    NSDictionary* params = @{@"relationId" : relationId,
                             @"uniqueId": @(handler.uniqueId),
                             @"type": @(type)};
    YWLog(@"%@",params);
    [[WMHttpTool shareHttpTool] deleteWithUrl:[YWCommonTool observerUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        YWLog(@"%s,error:%@", __func__, error.userInfo);
        if (complete) {
            complete(NO);
        }
    }];
}
@end
